package com.denghq.projectbuilder.component.nacos.config;

import com.alibaba.nacos.api.exception.NacosException;
import com.denghq.projectbuilder.common.util.BeanTool;
import com.denghq.projectbuilder.component.config.domain.ConfigAutoRegister;
import com.denghq.projectbuilder.component.config.metadata.ConfigDescriptor;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

@Slf4j
public class NacosConfigAutoRegister extends ConfigAutoRegister {
    private final List<ConfigDescriptor> configDescriptorList;
    private final NacosConfigManager nacosConfigManager;
    private final String appNo;

    public NacosConfigAutoRegister(List<ConfigDescriptor> configDescriptorList, NacosConfigManager nacosConfigManager, String appNo) {
        super(configDescriptorList, appNo);
        this.configDescriptorList = configDescriptorList;
        this.nacosConfigManager = nacosConfigManager;
        this.appNo = appNo;
    }

    @Override
    public List<ConfigDescriptor> getConfigsFromRemote(List<ConfigDescriptor> currentConfigs) {
        long timeout = nacosConfigManager.getNacosConfigProperties().getTimeout();
        String group = nacosConfigManager.getNacosConfigProperties().getGroup();
        List<ConfigDescriptor> configDescriptors = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(currentConfigs)) {
            currentConfigs.forEach(e -> {
                String categoryNo = e.getCategoryNo();
                try {
                    String config = nacosConfigManager.getConfigService().getConfig(categoryNo, group, timeout);
                    Optional.ofNullable(BeanTool.jsonStrToObject(config, ConfigDescriptor.class)).ifPresent(configDescriptors::add);
                } catch (NacosException ex) {
                    log.error("获取配置出错：categoryNo【{}】,错误信息{}", categoryNo, ex.getMessage());
                }
            });

        }
        return configDescriptors;
    }

    @Override
    public void writeConfigToRemote(List<ConfigDescriptor> configs) {

        if (!CollectionUtils.isEmpty(configs)) {
            configs.forEach(e -> {
                boolean res = writeConfigToRemote(e);
                if (!res) {
                    log.warn("写入配置到consul报错，配置信息：{}", e);
                }
            });
        }
    }

    private boolean writeConfigToRemote(ConfigDescriptor config) {
        Assert.notNull(config, "配置类不能为空！");
        Assert.isTrue(config.isAutoRegiste(), "只能注册属于本服务的配置，appNo非法:" + config.getAppNo());
        String group = nacosConfigManager.getNacosConfigProperties().getGroup();
        try {
            nacosConfigManager.getConfigService().publishConfig(config.getCategoryNo(), group, BeanTool.objectToJsonStr(config));
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
        return true;
    }
}
